package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 11752
 */
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * pre 请求过来之前执行
     * post 请求过来之后执行
     * @return 过滤类型
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器执行的顺序，数字越小越优先执行
     * @return 顺序号
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否开启true表示开启
     * @return 是否开启过滤器
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤内执行的操作，return任何object的值都表示继续执行
     * setSendZullResponse(false) 表示不在继续只能执行
     * @return 执行后返回的数据
     * @throws ZuulException 异常
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了");
        // 得到request上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取HttpServletRequest
        HttpServletRequest request = currentContext.getRequest();
        if ("OPTIONS".equals(request.getMethod())) {
            return null;
        }

        if (request.getRequestURI().indexOf("login") > 0) {
            return null;
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNoneBlank(authorization) && authorization.startsWith("Bearer ") ) {
            String token = authorization.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                String role = (String) claims.get("roles");
                if ("admin".equals(role)) {
                    //把头信息转发下去，并且放行
                    currentContext.addZuulRequestHeader("Authorization",authorization);
                    return null;
                }
            }catch (Exception e) {
                e.printStackTrace();
                currentContext.setSendZuulResponse(false);
            }
        }
        // 终止运行
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
